package com.ycb.seata;

import javax.sql.DataSource;
import javax.sql.XADataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import com.mysql.cj.jdbc.MysqlXADataSource;

import io.seata.rm.datasource.xa.DataSourceProxyXA;
import io.seata.tm.api.GlobalTransactionContext;

public class DBUtils {
 
	static String driver = "com.mysql.cj.jdbc.Driver";
	static String url = "jdbc:mysql://127.0.0.1:3306/db_temp?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
	static String username = "root";
	static String password = "root";

	public static SqlSession getSqlSession() {
		DataSource dataSource = new PooledDataSource(driver,url,username,password);
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
        configuration.addMapper(OrderMapper.class);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		return sqlSessionFactory.openSession();
	}

	
	/**
	 * seata 会话
	 * @return
	 */
	public static SqlSession getSeataSqlSession() {
		return getSeataSqlSessionFactory().openSession(true);
	}
	
	
	/**
	 * seata 会话
	 * @return
	 */
	public static SqlSessionFactory getSeataSqlSessionFactory() {
		DataSource dataSource = new PooledDataSource(driver,url,username,password);
		DataSourceProxyXA seataDataSourceProxy = new DataSourceProxyXA(dataSource);
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, seataDataSourceProxy);
		Configuration configuration = new Configuration(environment);
		configuration.addMapper(OrderMapper.class);
		return new SqlSessionFactoryBuilder()
				.build(configuration);
	}
	
}